import $ from 'jquery';
import { jwtDecode } from 'jwt-decode';

const ModuleUser = ({
    state: {
        id: "",
        username: "",
        photo: "",
        access: "",
        refresh: "",
        nickname: "",
        classname: "",
        collegename: "",
        phone_number: "",
        borrowCount: 0,
        is_login: false,
        is_superuser: false,
        password: "",
    },
    getters: {
    },
    mutations: {
        updateAccess(state, access) {
            state.access = access
        },
        updateUser(state, user) {
            state.id = user.id,
            state.username = user.username,
            state.photo = user.photo,
            state.borrowCount = user.borrowCount,
            state.access = user.access,
            state.refresh = user.refresh,
            state.is_login = user.is_login,
            state.nickname = user.nickname,
            state.classname = user.classname,
            state.collegename = user.collegename,
            state.phone_number = user.phone_number,
            state.password = user.password,
            state.is_superuser = user.is_superuser
        },
        logout(state) {
            state.id = "",
            state.username = "",
            state.photo = "",
            state.access = "",
            state.refresh = "",
            state.borrowCount = "",
            state.is_login = false,
            state.nickname = "",
            state.classname = "",
            state.collegename = "",
            state.phone_number = "",
            state.password = "",
            localStorage.removeItem('UserAccess');  
            localStorage.removeItem('UserRefresh');  
            localStorage.removeItem('Access_Obj');  
            localStorage.removeItem('classname');  
            localStorage.removeItem('collegename');  
            localStorage.removeItem('id');  
            localStorage.removeItem('is_superuser');  
            localStorage.removeItem('nickname');  
            localStorage.removeItem('password');  
            localStorage.removeItem('phone_number');  
            localStorage.removeItem('photo');  
            localStorage.removeItem('result');  
            localStorage.removeItem('username'); 
        },
    },
    actions: {
        startTokenRefresh({ commit }, refresh) {  
            setInterval(() => {  
                $.ajax({  
                    url: "http://47.121.28.202:8000/settings/token/refresh/", 
                    type: "POST",  
                    data: {  
                        refresh,  
                    },  
                    success(resp) {  
                        commit('updateAccess', resp.access);
                        const newAccess = resp.access;
                        localStorage.setItem('UserAccess', newAccess);  
                    },  
                });  
            }, 1000 * 4.50 * 60);  
        },  
        login(context ,data) {
            $.ajax({
                url: "http://47.121.28.202:8000/settings/token/",
                type: "POST",
                data: {
                    username: data.username,
                    password: data.password,
                },
                success(resp) {
                    const {access, refresh} = resp;
                    const access_obj = jwtDecode(access);
                    localStorage.setItem('UserRefresh', refresh);
                    localStorage.setItem('Access_Obj', JSON.stringify(access_obj));
                    localStorage.setItem('UserAccess', access);
                    context.dispatch('startTokenRefresh', refresh);
                    $.ajax({
                        url: "http://47.121.28.202:8000/settings/getinfo/",
                        type: "GET",
                        data: {
                            user_id: access_obj.user_id,
                        },
                        headers: {
                            'Authorization': "Bearer " + access,
                        },
                        success(resp) {
                            localStorage.setItem('classname', resp.classname);
                            localStorage.setItem('collegename', resp.collegename);
                            localStorage.setItem('id', resp.id);
                            localStorage.setItem('is_superuser', resp.is_superuser);
                            localStorage.setItem('nickname', resp.nickname);
                            localStorage.setItem('password', resp.password);
                            localStorage.setItem('phone_number', resp.phone_number);
                            localStorage.setItem('photo', resp.photo);
                            localStorage.setItem('result', resp.result);
                            localStorage.setItem('username', resp.username);
                            context.commit("updateUser", {
                                ...resp,
                                access: access,
                                refresh: refresh,
                                is_login: true
                            });
                            data.success();
                        }
                    })
                },
                error() {
                    data.error();
                }
            })
        },
        autoLogin({ commit, dispatch }) {  
            const classname = localStorage.getItem('classname');
            const collegename = localStorage.getItem('collegename');
            const is_superuser = localStorage.getItem('is_superuser');
            const nickname = localStorage.getItem('nickname');
            const password = localStorage.getItem('password');
            const phone_number = localStorage.getItem('phone_number');
            const photo = localStorage.getItem('photo');
            const result = localStorage.getItem('result');
            const username = localStorage.getItem('username');
            const access = localStorage.getItem('UserAccess');  
            const refresh = localStorage.getItem('UserRefresh');  
            const accessObjStr = localStorage.getItem('Access_Obj'); 
            if (access && refresh && accessObjStr) {
                try {  
                    const accessObj = JSON.parse(accessObjStr); 
                    commit("updateUser", {  
                        id: accessObj.user_id,
                        access_obj: accessObj,
                        access: access,  
                        refresh: refresh,  
                        is_login: true,
                        classname: classname,
                        collegename: collegename,
                        is_superuser: is_superuser === 'true',
                        nickname: nickname,
                        password: password,
                        phone_number: phone_number,
                        photo: photo,
                        result: result,
                        username: username,   
                    }); 
                    dispatch('startTokenRefresh', refresh); 
                } catch (error) {  
                    console.error("Error parsing stored access token:", error);  
                    localStorage.removeItem('UserAccess');  
                    localStorage.removeItem('UserRefresh');  
                    localStorage.removeItem('Access_Obj');  
                } 
            }
        }
    },
    modules: {
    }
});

export default ModuleUser